package cz.proks.simplecalendarmanager.server.servlet;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.google.gdata.client.authn.oauth.GoogleOAuthHelper;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gwt.user.client.rpc.InvocationException;

import cz.proks.simplecalendarmanager.server.Configuration;
import cz.proks.simplecalendarmanager.server.utils.ServletUtils;
import cz.proks.simplecalendarmanager.shared.model.AccessToken;

public class OAuthAccessServlet extends HttpServlet {
	private final static Logger log = Logger.getLogger(OAuthAccessServlet.class.getSimpleName());
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
					throws ServletException, IOException {
		log.info("service():: start");
		
		String requestContent = ServletUtils.toString(request.getInputStream());
		log.info("service():: request=" + requestContent);
		
		try {
			String appScope = request.getParameter("appScope");
			
			AccessToken grantAccessToken = ServletUtils.getAccessTokenFromSession(appScope, request.getSession());
			
			log.info("service():: original accessToken=" + grantAccessToken != null ? grantAccessToken.toString() : "null");
			
			GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
			oauthParameters.setOAuthConsumerKey(Configuration.getConsumerToken());
			oauthParameters.setOAuthConsumerSecret(Configuration.getConsumerTokenSecret());
			oauthParameters.setOAuthTokenSecret(grantAccessToken.getOAuthTokenSecret());
			
			// retrieve access token
			GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
			oauthHelper.getOAuthParametersFromCallback(request.getQueryString(), oauthParameters);
			oauthHelper.getAccessToken(oauthParameters); // !!!
			
			String accessToken = oauthParameters.getOAuthToken();			
			String accessTokenSecret = oauthParameters.getOAuthTokenSecret();
			
			grantAccessToken.setOAuthToken(accessToken);
			grantAccessToken.setOAuthTokenSecret(accessTokenSecret);
			
			ServletUtils.setAccessTokenToSession(appScope, grantAccessToken, request.getSession());
			
			log.info("service():: accessToken=" + grantAccessToken != null ? grantAccessToken.toString() : "null");						
		} catch (Exception e) {
			log.log(Level.WARNING, "service():: ", e);			
		}
		
		response.sendRedirect(Configuration.getHomeUrl());
		
		log.info("service():: exit");
	}	
}
